/*
encoder 例子
+++: 1 添加初始化/ttyUSB0视频数据出口

*/
#include "bsp_encoder.h"
#include "bsp_uart.h"
#include "bsp_pthread.h"
#include "bsp_video.h"
int main(int argc, char **argv)
{
    //分配并初始化编码器线程上下文
    ThreadDevContext* ctx = (ThreadDevContext*)malloc(sizeof(ThreadDevContext));
    memset(ctx, 0, sizeof(ThreadDevContext));
    //初始化互斥锁和条件变量
    pthread_mutex_init(&ctx->lock, NULL);
    pthread_cond_init(&ctx->cond, NULL);
    //设置初始状态
    // ctx->thdstate = ;
    ctx->thdstop_flag = false;
    //配置视频参数
    ctx->args = (ThreadDevArgs*)malloc(sizeof(ThreadDevArgs)); // 添加这一行
    memset(ctx->args, 0, sizeof(ThreadDevArgs));

// 分配 video 和 uart 结构体内存
    ctx->args->video         = (Video_t*)malloc(sizeof(Video_t));
    ctx->args->video->width  = 640;
    ctx->args->video->height = 480;
    ctx->args->video->fps    = 25;
    ctx->args->video->devnum = 0;
    ctx->args->video->fmt    = MPP_FMT_YUV420SP;
    // 配置UART参数
    ctx->args->uart              = (Uart_t*)malloc(sizeof(Uart_t));
    ctx->args->uart->name        = strdup("/dev/ttyUSB0"); // 使用strdup分配内存
    ctx->args->uart->fd          = -1;
    /*ttyUSB0 video out stream init*/
    ctx->args->uart->baud_rate   = 3000000;
    ctx->args->uart->data_bits   = 8;
    ctx->args->uart->stop_bits   = 1;
    ctx->args->uart->parity      = 'N';

    uart_init(ctx->args->uart,O_RDWR | O_NOCTTY | O_NONBLOCK);
    uart_show_data(ctx->args->uart);

    // 创建编码器线程
    pthread_t enc_thd;  //定义线程ID变量，而不是指针
    int ret;
    // 创建编码器线程并传递上下文
    ret = pthread_create(&enc_thd, NULL, encoder_thd1, ctx);
    if (ret != 0) {
        fprintf(stderr, "Failed to create encoder thread: %s\n", strerror(ret));
        // 清理资源
        safe_free(ctx->args->uart->name);
        safe_free(ctx->args->uart->basicargs);
        uart_deinit(ctx->args->uart);
        safe_free(ctx->args->video);
        safe_free(ctx->args);
        safe_free(ctx);
        return -1;
    }
    printf("Encoder thread started (ID: %lu)\n", (unsigned long)enc_thd);

    // 等待用户输入停止命令
    printf("Press Enter to stop the encoder...\n");
    getchar();

    // 请求线程停止
    pthread_mutex_lock(&ctx->lock);
    ctx->thdstop_flag = true;
    pthread_cond_signal(&ctx->cond); // 通知线程
    pthread_mutex_unlock(&ctx->lock);

    // 等待线程结束
    ret = pthread_join(enc_thd, NULL);
    if (ret != 0) {
        fprintf(stderr, "Failed to join encoder thread: %s\n", strerror(ret));
    }

    // 清理资源
    safe_free(ctx->args->uart->name);
    safe_free(ctx->args->uart);
    uart_deinit(ctx->args->uart);
    safe_free(ctx->args->video);
    safe_free(ctx->args);
    
    pthread_mutex_destroy(&ctx->lock);
    pthread_cond_destroy(&ctx->cond);

    safe_free(ctx);

    printf("Encoder thread completed\n");
    return 0;
}